package com.zero.xiaodai.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import com.google.common.base.Strings;

public class ZipUtil {
	private static final int buffer = 2048;
	

	private static final List<String> sheetNames = new ArrayList<>();
	private static final List<String[][]> valuesList = new ArrayList<>();

	/**
	 * 解压Zip文件
	 * 
	 * @param path 文件目录
	 */
	/*
	 * public static void unZip(String path) { int count = -1; String savepath = "";
	 * File file = null; InputStream is = null; FileOutputStream fos = null;
	 * BufferedOutputStream bos = null; savepath = path.substring(0,
	 * path.lastIndexOf(".")) + File.separator; // 保存解压文件目录 new
	 * File(savepath).mkdir(); // 创建保存目录 ZipFile zipFile = null; try { zipFile = new
	 * ZipFile(path, "gbk"); // 解决中文乱码问题 Enumeration<?> entries =
	 * zipFile.getEntries(); while (entries.hasMoreElements()) { byte buf[] = new
	 * byte[buffer]; ZipEntry entry = (ZipEntry) entries.nextElement(); String
	 * filename = entry.getName(); boolean ismkdir = false; if
	 * (filename.lastIndexOf("/") != -1) { // 检查此文件是否带有文件夹 ismkdir = true; }
	 * filename = savepath + filename; if (entry.isDirectory()) { // 如果是文件夹先创建 file
	 * = new File(filename); file.mkdirs(); continue; } file = new File(filename);
	 * if (!file.exists()) { // 如果是目录先创建 if (ismkdir) { new
	 * File(filename.substring(0, filename.lastIndexOf("/"))).mkdirs(); // 目录先创建 } }
	 * file.createNewFile(); // 创建文件 is = zipFile.getInputStream(entry); fos = new
	 * FileOutputStream(file); bos = new BufferedOutputStream(fos, buffer); while
	 * ((count = is.read(buf)) > -1) { bos.write(buf, 0, count); } bos.flush();
	 * bos.close(); fos.close(); is.close(); } zipFile.close(); } catch (IOException
	 * ioe) { ioe.printStackTrace(); } finally { try { if (bos != null) {
	 * bos.close(); } if (fos != null) { fos.close(); } if (is != null) {
	 * is.close(); } if (zipFile != null) { zipFile.close(); } } catch (Exception e)
	 * { e.printStackTrace(); } } }
	 */

	/**
	 * 解压到指定目录
	 */
	public static void unZipFiles(String zipPath, String descDir) throws IOException {
		unZipFiles(new File(zipPath), descDir);
	}

	/**
	 * 解压文件到指定目录
	 */
	@SuppressWarnings("rawtypes")
	public static void unZipFiles(File zipFile, String descDir) throws IOException {
		File pathFile = new File(descDir);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
		// 解决zip文件中有中文目录或者中文文件
		ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
		for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			String zipEntryName = entry.getName();
			InputStream in = zip.getInputStream(entry);
			String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
			
			// 判断路径是否存在,不存在则创建文件路径
			File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
			if (!file.exists()) {
				file.mkdirs();
			}
			// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
			if (new File(outPath).isDirectory()) {
				continue;
			}
			// 输出文件路径信息
			System.out.println(outPath);
			OutputStream out = new FileOutputStream(outPath);
			byte[] buf1 = new byte[1024];
			int len;
			while ((len = in.read(buf1)) > 0) {
				out.write(buf1, 0, len);
			}
			in.close();
			out.close();
		}
		System.out.println("******************解压完毕********************");
	}

	/*
	 * public static void unrar(String sourceRarPath, String destDirPath) throws
	 * Exception { File sourceRar = new File(sourceRarPath); File destDir = new
	 * File(destDirPath); Archive archive = null; FileOutputStream fos = null;
	 * System.out.println("Starting 开始解压..."); try { archive = new
	 * Archive(sourceRar); FileHeader fh = archive.nextFileHeader(); int count = 0;
	 * File destFileName = null; while (fh != null) { System.out.println((++count) +
	 * ") " + fh.getFileNameString()); String compressFileName =
	 * fh.getFileNameString().trim(); destFileName = new
	 * File(destDir.getAbsolutePath() + "/" + compressFileName); if
	 * (fh.isDirectory()) { if (!destFileName.exists()) { destFileName.mkdirs(); }
	 * fh = archive.nextFileHeader(); continue; } if
	 * (!destFileName.getParentFile().exists()) {
	 * destFileName.getParentFile().mkdirs(); } fos = new
	 * FileOutputStream(destFileName); archive.extractFile(fh, fos); fos.close();
	 * fos = null; fh = archive.nextFileHeader(); } archive.close(); archive = null;
	 * System.out.println("Finished 解压完成!"); } catch (Exception e) { throw e; }
	 * finally { if (fos != null) { try { fos.close(); fos = null; } catch
	 * (Exception e) { } } if (archive != null) { try { archive.close(); archive =
	 * null; } catch (Exception e) { } } } }
	 */
	public static void unRar(File rarFile, String outDir) throws Exception {
		File outFileDir = new File(outDir);
		if (!outFileDir.exists()) {
			boolean isMakDir = outFileDir.mkdirs();
			if (isMakDir) {
				System.out.println("创建压缩目录成功");
			}
		}
		Archive archive = new Archive(new FileInputStream(rarFile));
		FileHeader fileHeader = archive.nextFileHeader();
		while (fileHeader != null) {
			if (fileHeader.isDirectory()) {
				fileHeader = archive.nextFileHeader();
				continue;
			}
			String fileName=Strings.isNullOrEmpty(fileHeader.getFileNameW())?fileHeader.getFileNameString():fileHeader.getFileNameW();
			File out = new File(outDir + File.separator+fileName/*fileHeader.getFileNameString()*/);
			if (!out.exists()) {
				if (!out.getParentFile().exists()) {
					out.getParentFile().mkdirs();
				}
				out.createNewFile();
			}
			FileOutputStream os = new FileOutputStream(out);
			archive.extractFile(fileHeader, os);

			os.close();

			fileHeader = archive.nextFileHeader();
		}
		archive.close();
	}
	
	
	
	public static void unRarInputStream(FileInputStream in, String outDir) throws Exception {
		File outFileDir = new File(outDir);
		if (!outFileDir.exists()) {
			boolean isMakDir = outFileDir.mkdirs();
			if (isMakDir) {
				System.out.println("创建压缩目录成功");
			}
		}
		Archive archive = new Archive(in);
		FileHeader fileHeader = archive.nextFileHeader();
		while (fileHeader != null) {
			if (fileHeader.isDirectory()) {
				fileHeader = archive.nextFileHeader();
				continue;
			}
			String fileName=Strings.isNullOrEmpty(fileHeader.getFileNameW())?fileHeader.getFileNameString():fileHeader.getFileNameW();
			File out = new File(outDir + File.separator+fileName/*fileHeader.getFileNameString()*/);
			if (!out.exists()) {
				if (!out.getParentFile().exists()) {
					out.getParentFile().mkdirs();
				}
				out.createNewFile();
			}
			FileOutputStream os = new FileOutputStream(out);
			archive.extractFile(fileHeader, os);

			os.close();

			fileHeader = archive.nextFileHeader();
		}
		archive.close();
	}
	/*
	 * public static void main(String[] args) {
	 * 
	 * String filePath="H:\\test/北仑档案样例数据.rar"; String
	 * format=filePath.substring(filePath.indexOf(".")+1);
	 * if(format.equalsIgnoreCase("rar")) {
	 * 
	 * }else if(format.equalsIgnoreCase("zip")) { unZipFiles(filePath, descDir); }
	 * 
	 * unZip("F:\\110000002.zip"); String f = "F:\\110000002"; File file = new
	 * File(f); String[] test = file.list(); for (int i = 0; i < test.length; i++) {
	 * System.out.println(test[i]); } System.out.println("------------------");
	 * String fileName = ""; File[] tempList = file.listFiles(); for (int i = 0; i <
	 * tempList.length; i++) { if (tempList[i].isFile()) {
	 * System.out.println("文   件：" + tempList[i]); fileName = tempList[i].getName();
	 * System.out.println("文件名：" + fileName); } if (tempList[i].isDirectory()) {
	 * System.out.println("文件夹：" + tempList[i]); } } }
	 */

	public static void main(String[] args) throws IOException {
		/**
		 * 解压文件
		 */

		try {

			HSSFWorkbook wb = null;
			String filePath = "H:\\test/zipfile.zip";
			String descDir = "H:\\test/zipfile/";
			String format = filePath.substring(filePath.indexOf(".") + 1);
			if (format.equalsIgnoreCase("rar")) {
				File rarFile = new File(filePath);
				unRar(rarFile, descDir);

			} else if (format.equalsIgnoreCase("zip")) {
				unZipFiles(filePath, descDir);
			}
			
			List<List<String>> filePathList=new ArrayList<>();
			List<String> filePaths=new ArrayList<>();
			FileListUtil.DirAll(new File(descDir), sheetNames,valuesList,filePathList,filePaths);
			String[] title = {"序号","年份","证号","名称"};
			for(List<String> fps:filePathList) {
				String [][]values=new String[fps.size()][4];
				for(int z=0;z<fps.size();z++) {
					String fp=fps.get(z);
					String[] fpArr=fp.split("\\\\");
					String year="";
					String num="";
					String name="";
					for(int k=0;k<fpArr.length;k++) {
						String f=fpArr[k];
						if(f.matches("[0-9]+")) {
							year=f;
							if(k+2>=fpArr.length) {
								name=fpArr[k+1];
							}else {
								num=fpArr[k+1];
								name=fpArr[k+2];
							}
						}
					}
					if(!Strings.isNullOrEmpty(year)) {
						values[z][0]=(z+1)+"";
						values[z][1]=year;
						values[z][2]=num;
						values[z][3]=name;
					}
					
				}
				valuesList.add(values);
			}
			
			
			wb = ExcelWriteHelper.getHSSFWorkbooks(sheetNames, title, valuesList, wb);
			
			OutputStream os = new FileOutputStream("H:\\test/北仑档案样例数据.xls");
			wb.write(os);

			os.flush();
			os.close();
			
			// 响应到客户端
//			try {
//				setResponseHeader(response, fileName);
//				OutputStream os = response.getOutputStream();
//				wb.write(os);
//				os.flush();
//				os.close();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	// 发送响应流方法
		private void setResponseHeader(HttpServletResponse response, String fileName) {
			try {
				try {
					fileName = new String(fileName.getBytes(), "ISO8859-1");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				response.setContentType("application/octet-stream;charset=utf-8");
				response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
				response.addHeader("Pargam", "no-cache");
				response.addHeader("Cache-Control", "no-cache");
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

}
